<?php
/**
 * Created by PhpStorm.
 * User: 96151
 * Date: 2018/7/27
 * Time: 14:48
 */
namespace app\common\service;
use app\common\library\CommonFun;
use PHPQRCode\QRcode;

/**
 * Class QRCodeLoginService   APP二维码登录
 */
class QRCodeLoginService
{
    /**
     * @var int 失效时间
     */
    private static $failure_time = 120;

    /**
     * @var int 绑定关系时效性
     */
    private static $binding_failure_time = 60;

    /**
     * @var string 唯一标识缓存key前缀
     */
    private static $uuid_cache_prefix = 'qrUuid_';

    /**
     * @var string 绑定关系key前缀
     */
    private static $binding_cache_prefix = 'login_';

    /**
     * 生成唯一编号区分
     */
    public static function getQRCode()
    {
        $memcacheObj = CommonFun::get_memcache( 'default' );
        $qrUuid = md5(uniqid(mt_rand(), true));

        // 缓存唯一标识
        $res = $memcacheObj->set( self::$uuid_cache_prefix.$qrUuid, 0, self::$failure_time );
        if ( !$res ){
            return false;
        }

        return $qrUuid;
    }

    /**
     * 时效性检测
     * @param $qrUuid
     * @return bool
     */
    public static function check( $qrUuid ){
        $memcacheObj = CommonFun::get_memcache( 'default' );
        $res = $memcacheObj->get( self::$uuid_cache_prefix.$qrUuid );
        return $res=== false ? false : true;
    }

    /**
     * 绑定用户和唯一标识
     * @param $user_id
     * @param $qrUuid
     * @return bool
     */
    public static function setUser( $user_id, $qrUuid ){
        $memcacheObj = CommonFun::get_memcache( 'default' );
        $res = $memcacheObj->set( self::$binding_cache_prefix.$qrUuid, $user_id, self::$binding_failure_time );
        return $res;
    }

    /**
     * 通过唯一标识生成二维码
     */
    public static function setQRCode( $qrUuid ){
        $url =  U('/capi/WzArticle/detail',array( 'qrUuid'=>$qrUuid ) );
        vendor("phpqrcode.phpqrcode");
        $level = 'L';
        // 点的大小：1到10,用于手机端4就可以了
        $size = 7;
        // 下面注释了把二维码图片保存到本地的代码,如果要保存图片,用$fileName替换第二个参数false
        // $path = __IMG__;
        // 生成的文件名
        // $fileName = $path.$size.'.png';
        QRcode::png($url, false, $level, $size, 0);
    }

























}